package com.example.zzx.dovebook.setting

import android.content.SharedPreferences
import android.os.Bundle
import android.os.Handler
import android.preference.Preference
import android.preference.PreferenceManager
import android.view.MenuItem
import com.example.baselibrary.image.GlideManager
import com.example.zzx.dovebook.R

class OverSettingActivity : AppCompatPreferenceActivity() {

    lateinit var defaultSp : SharedPreferences

    val mainHandler = Handler()

    private val summaryBindListener = Preference.OnPreferenceChangeListener { preference, value ->
        val stringValue = value.toString()
        when (preference.key) {
            getString(R.string.setting_clear_buffer_key) ->
                preference.summary = stringValue
        }
        true
    }

    private val onPreferenceClickListener = Preference.OnPreferenceClickListener {preference ->

        when (preference.key) {
            getString(R.string.setting_clear_buffer_key) -> {
                GlideManager.clearDiskCache(this) { restSize ->
                    mainHandler.post {
                        defaultSp.edit().putString(getString(R.string.setting_clear_buffer_key), restSize)
                        summaryBindListener.onPreferenceChange(preference, restSize)
                    }
                }
            }
        }

        true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setupActionBar()
        defaultSp = PreferenceManager.getDefaultSharedPreferences(this)
        addPreferencesFromResource(R.xml.setting_preference)
        listView.dividerHeight = 0
        initPreferences()
    }

    private fun initPreferences() {

        initBufferPre()
    }

    private fun initBufferPre() {
        val bufferPre = findPreference(getString(R.string.setting_clear_buffer_key))
        bufferPre.onPreferenceChangeListener = summaryBindListener
        bufferPre.onPreferenceClickListener = onPreferenceClickListener
        defaultSp.edit()
                .putString(getString(R.string.setting_clear_buffer_key), GlideManager.getDiskCacheSize(this))
                .commit()
        summaryBindListener.onPreferenceChange(bufferPre,
                defaultSp.getString(getString(R.string.setting_clear_buffer_key), "0.0Byte"))
    }

    private fun setupActionBar() {
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.title = getString(R.string.activity_setting)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {

        when (item.itemId) {
            android.R.id.home -> finish()
        }

        return super.onOptionsItemSelected(item)
    }

}